// pages/camera-detect/camera-detect.js
const app = getApp()

Page({
  data: {
    showCamera: false,
    isScanning: false,
    flashEnabled: false,
    screenLightEnabled: false,
    flashMode: 'off',
    suspiciousPoints: [],
    detectionStartTime: null,
    cameraContext: null,
    screenBrightness: 1,
    showGuide: false
  },

  onLoad() {
    console.log('镜头反光检测页面加载')
    this.initCamera()
  },

  onShow() {
    // 保持屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
  },

  onHide() {
    this.cleanup()
  },

  onUnload() {
    this.cleanup()
  },

  // 清理资源
  cleanup() {
    this.stopScanning()
    wx.setKeepScreenOn({
      keepScreenOn: false
    })
    // 恢复屏幕亮度
    if (this.data.screenLightEnabled) {
      wx.setScreenBrightness({
        value: this.data.screenBrightness
      })
    }
  },

  // 初始化相机
  initCamera() {
    // 检查相机权限
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.camera'] === false) {
          wx.showModal({
            title: '需要相机权限',
            content: '镜头反光检测需要使用相机功能',
            showCancel: false,
            confirmText: '去设置',
            success: () => {
              wx.openSetting({
                success: (settingRes) => {
                  if (settingRes.authSetting['scope.camera']) {
                    this.setData({
                      showCamera: true
                    })
                    this.data.cameraContext = wx.createCameraContext()
                  }
                }
              })
            }
          })
        } else if (res.authSetting['scope.camera'] === undefined) {
          // 权限未询问过，直接尝试使用
          this.setData({
            showCamera: true
          })
          this.data.cameraContext = wx.createCameraContext()
        } else {
          // 权限已授权
          this.setData({
            showCamera: true
          })
          this.data.cameraContext = wx.createCameraContext()
        }
      },
      fail: () => {
        console.error('获取设置失败')
        // 在开发工具中直接显示相机
        this.setData({
          showCamera: true
        })
        this.data.cameraContext = wx.createCameraContext()
      }
    })
  },

  // 相机就绪
  cameraReady() {
    console.log('相机初始化完成')
    wx.showToast({
      title: '相机就绪',
      icon: 'success',
      duration: 1500
    })
  },

  // 相机错误
  cameraError(e) {
    console.error('相机错误:', e.detail)
    wx.showModal({
      title: '相机启动失败',
      content: '请检查相机权限或重新启动应用',
      showCancel: false
    })
  },

  // 相机停止
  cameraStop() {
    console.log('相机停止')
    this.setData({
      showCamera: false,
      isScanning: false
    })
  },

  // 开始检测
  startScanning() {
    if (!this.data.showCamera) {
      wx.showToast({
        title: '相机未就绪',
        icon: 'error'
      })
      return
    }

    this.setData({
      isScanning: true,
      detectionStartTime: Date.now(),
      suspiciousPoints: []
    })

    // 自动开启闪光灯
    if (!this.data.flashEnabled) {
      this.toggleFlash()
    }

    wx.showToast({
      title: '开始检测',
      icon: 'success',
      duration: 2000
    })

    wx.showModal({
      title: '检测提示',
      content: '请关闭房间灯光，使用闪光灯缓慢扫描可疑区域。如发现异常反光点，请拍照记录。',
      showCancel: false
    })
  },

  // 停止检测
  stopScanning() {
    this.setData({
      isScanning: false
    })

    wx.showToast({
      title: '检测已停止',
      icon: 'none'
    })
  },

  // 手动添加可疑点（用户发现异常时调用）
  addSuspiciousPoint(x, y, intensity) {
    const point = {
      x: x || Math.random() * 300 + 50,
      y: y || Math.random() * 200 + 50,
      intensity: intensity || 75,
      timestamp: Date.now()
    }

    this.setData({
      suspiciousPoints: [...this.data.suspiciousPoints, point]
    })

    wx.vibrateShort()
    console.log('添加可疑点:', point)
  },

  // 切换闪光灯
  toggleFlash() {
    const flashEnabled = !this.data.flashEnabled
    const flashMode = flashEnabled ? 'torch' : 'off'
    
    this.setData({
      flashEnabled,
      flashMode
    })

    wx.showToast({
      title: flashEnabled ? '闪光灯已开启' : '闪光灯已关闭',
      icon: 'none'
    })
  },

  // 切换屏幕补光
  toggleScreenLight() {
    const screenLightEnabled = !this.data.screenLightEnabled
    
    if (screenLightEnabled) {
      // 获取当前亮度
      wx.getScreenBrightness({
        success: (res) => {
          this.setData({
            screenBrightness: res.value
          })
          
          // 设置最大亮度
          wx.setScreenBrightness({
            value: 1
          })
        }
      })
    } else {
      // 恢复原始亮度
      wx.setScreenBrightness({
        value: this.data.screenBrightness
      })
    }

    this.setData({
      screenLightEnabled
    })

    wx.showToast({
      title: screenLightEnabled ? '屏幕补光已开启' : '屏幕补光已关闭',
      icon: 'none'
    })
  },

  // 拍照记录
  takePhoto() {
    if (!this.data.cameraContext) {
      wx.showToast({
        title: '相机未就绪',
        icon: 'error'
      })
      return
    }

    this.data.cameraContext.takePhoto({
      quality: 'high',
      success: (res) => {
        console.log('拍照成功:', res.tempImagePath)
        
        // 保存照片到相册
        wx.saveImageToPhotosAlbum({
          filePath: res.tempImagePath,
          success: () => {
            wx.showToast({
              title: '照片已保存',
              icon: 'success'
            })
          },
          fail: () => {
            wx.showToast({
              title: '保存失败',
              icon: 'error'
            })
          }
        })
      },
      fail: (err) => {
        console.error('拍照失败:', err)
        wx.showToast({
          title: '拍照失败',
          icon: 'error'
        })
      }
    })
  },

  // 定位可疑点
  locatePoint(e) {
    const index = e.currentTarget.dataset.index
    const point = this.data.suspiciousPoints[index]
    
    wx.showModal({
      title: `可疑点 ${index + 1}`,
      content: `位置: (${Math.floor(point.x)}, ${Math.floor(point.y)})\n强度: ${point.intensity}\n发现时间: ${new Date(point.timestamp).toLocaleTimeString()}`,
      showCancel: false
    })
  },

  // 保存检测结果
  saveResult() {
    if (!this.data.detectionStartTime) {
      wx.showToast({
        title: '请先开始检测',
        icon: 'error'
      })
      return
    }

    const result = {
      id: app.utils.generateId(),
      timestamp: Date.now(),
      location: '', // 用户可以手动输入
      detectType: 'camera',
      result: {
        camera: {
          suspiciousPoints: this.data.suspiciousPoints,
          photos: [], // 这里可以记录拍摄的照片路径
          duration: Date.now() - this.data.detectionStartTime
        }
      },
      riskLevel: app.utils.assessRiskLevel({
        camera: { suspiciousPoints: this.data.suspiciousPoints }
      }),
      notes: ''
    }

    // 获取现有记录
    const history = wx.getStorageSync('detection_history') || []
    history.unshift(result)
    
    // 保存到本地存储
    wx.setStorageSync('detection_history', history)

    wx.showModal({
      title: '保存成功',
      content: `检测结果已保存到历史记录\n发现可疑点: ${this.data.suspiciousPoints.length} 个\n风险等级: ${result.riskLevel}`,
      showCancel: false,
      success: () => {
        // 询问是否跳转到历史页面
        wx.showModal({
          title: '查看历史',
          content: '是否跳转到历史记录页面查看详情？',
          success: (res) => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/history/history'
              })
            }
          }
        })
      }
    })
  },

  // 清除结果
  clearResults() {
    wx.showModal({
      title: '确认清除',
      content: '是否清除当前检测结果？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            suspiciousPoints: []
          })
          wx.showToast({
            title: '已清除结果',
            icon: 'success'
          })
        }
      }
    })
  },

  // 切换指南面板
  toggleGuide() {
    this.setData({
      showGuide: !this.data.showGuide
    })
  },

  // 分享给好友
  onShareAppMessage() {
    const suspiciousCount = this.data.suspiciousPoints.length
    return {
      title: suspiciousCount > 0 ? 
        `镜头检测发现 ${suspiciousCount} 个可疑点 - 安心住助手` : 
        '镜头反光检测工具 - 安心住助手',
      desc: '使用相机和闪光灯检测隐藏的针孔摄像头',
      path: '/pages/camera-detect/camera-detect'
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '镜头反光检测 - 安心住助手',
      query: 'tool=camera'
    }
  }
})
